<script setup lang="ts">
import {defineOptions, reactive, ref} from 'vue';
import Cookies from 'js-cookie';
import {getCodeImgGET} from '@/services/login';
import {useUserStore} from '@/models/user';
import {encrypt, decrypt} from '@/utils/jsencrypt';

defineOptions({name: 'OtherLogin'});

interface FormState {
  username: string | undefined;
  password: string | undefined;
  remember: boolean;
  code: string;
  uuid: string;
}
const userModel = useUserStore();

const formState = reactive<FormState>({
  username: 'admin',
  password: 'admin123',
  remember: false,
  code: '',
  uuid: '',
});
const formRules = reactive({
  username: [{required: true, trigger: 'blur', message: '请输入您的账号'}],
  password: [{required: true, trigger: 'blur', message: '请输入您的密码'}],
  code: [{required: true, trigger: 'change', message: '请输入验证码'}],
});

const codeUrl = ref(
  '',
);
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);

// 获取验证码
const getCode = () => {
  getCodeImgGET().then((res) => {
    codeUrl.value = 'data:image/gif;base64,' + res.img;
    formState.uuid = res.uuid;
  });
};
const getCookie = () => {
  const username = Cookies.get('username') || formState.username;
  const password = Cookies.get('password');
  const remember: boolean | string = Cookies.get('remember') || false;
  formState.username = username;
  formState.password = password === undefined ? formState.password : decrypt(password);
  formState.remember = Boolean(remember);
};

const onFinishLogin = (values: any) => {
  // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
  if (formState.remember && formState.username && formState.password) {
    Cookies.set('username', formState.username, {expires: 30});
    Cookies.set('password', encrypt(formState.password), {expires: 30});
    Cookies.set('remember', formState.remember as any, {expires: 30});
  } else {
    // 否则移除
    Cookies.remove('username');
    Cookies.remove('password');
    Cookies.remove('remember');
  }
  const bodyData = {
    ...formState,
    username: formState.username?.trim(),
    password: formState.password?.trim(),
  };
  loading.value = true;
  userModel.login({
    bodyData,
    callback: () => {
      loading.value = false;
      getCode();
    },
  });

  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
getCode();
getCookie();
</script>

<template>
  <div class="app-login">
    <div class="container">
      <div class="title">登陆</div>
      <a-form
        name="basic"
        :model="formState"
        :rule="formRules"
        :label-col="{span: 6}"
        :wrapper-col="{span: 18}"
        autocomplete="off"
        @finish="onFinishLogin"
        @finishFailed="onFinishFailed"
        style="margin-top: 20px"
      >
        <a-form-item label="用户名" name="username" :rules="[{required: true, message: '请输入用户'}]">
          <a-input v-model:value="formState.username" />
        </a-form-item>

        <a-form-item label="密码" name="password" :rules="[{required: true, message: '请输入用户密码'}]">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item label="验证码" name="code" :rules="[{required: true, message: '请输入用户验证码'}]">
          <a-row justify="center">
            <a-col :span="16"> <a-input v-model:value="formState.code" /></a-col>
            <a-col :span="8">
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img" />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item name="remember" :wrapper-col="{offset: 6, span: 18}">
          <a-checkbox v-model:checked="formState.remember">记住密码</a-checkbox>
        </a-form-item>
        <a-form-item :wrapper-col="{offset: 6, span: 18}">
          <a-button type="primary" html-type="submit" :loading="loading">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<style scoped lang="less">
.app-login {
  height: 100vh;
  background: gray;
  display: flex;
  align-items: center;
  justify-content: center;
  .container {
    width: 420px;
    background: #fff;
    border-radius: 5px;
    padding: 20px 20px;
    .title {
      text-align: center;
    }
    .login-code {
      height: 31px;
      img {
        cursor: pointer;
        vertical-align: middle;
      }
      .login-code-img {
        height: 31px;
        margin-left: 12px;
      }
    }
  }
}
</style>
